const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const usersFilePath = path.join(__dirname, '../json/users.json');  // 用户信息存储路径

// 读取 JSON 文件中的数据
const readJsonData = (filePath) => {
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
};

// 登录接口
exports.login = (req, res) => {
    console.log("登录请求数据:", req.body);
    const {username, password} = req.body;

    if (!username || !password) {
        return res.status(400).json({error: '用户名和密码不能为空'});
    }

    const users = readJsonData(usersFilePath);

    const user = users.find(user => user.username === username && user.password === password);

    if (!user || user.password !== password) {
        return res.status(401).json({
            code: 1,
            content: null,
            message: '用户名或密码错误'
        });
    }

    // JWT token
    const token = jwt.sign({username: user.username}, 'your_secret_key', {expiresIn: '5h'});

    res.json({
        code: 0,
        message: '登录成功',
        token: token
    });
};
